const STORAGE_KEY = 'todos';
// localStorage中存储任务的键名

class TodoAPI {
    // 初始化本地储存
    static initStorage(){
        if(!localStorage.getItem(STORAGE_KEY)){
            localStorage.setItem(STORAGE_KEY,JSON.stringify([]))
        }
    }


/** 
*  @returns {Promise<Array>} 返回待办事项数组的Promise
*/
    static async getAllTodos() {
        try {
            // 确保存储已初始化
            this.initStorage();
            
            // 从localStorage获取数据
            const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            
            // 模拟网络延迟
            await new Promise(resolve => setTimeout(resolve, 300));
            
            return todos;
        } catch (error) {
            console.error('获取任务列表出错:', error);
            throw error;
        }
    }
    


 /**
     * 根据ID获取单个待办事项
     * @param {number} id - 待办事项ID
     * @returns {Promise<Object>} 返回待办事项对象的Promise
     */


    static async getTodoById(id) {
        try {
            const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            const todo = todos.find(item => item.id === id);
            
            if (!todo) {
                throw new Error(`找不到ID为${id}的任务`);
            }
            
            // 模拟网络延迟
            await new Promise(resolve => setTimeout(resolve, 200));
            
            return todo;
        } catch (error) {
            console.error(`获取任务ID=${id}出错:`, error);
            throw error;
        }
    }


     /**
     * 根据ID获取单个待办事项
     * @param {number} id - 待办事项ID
     * @returns {Promise<Object>} 返回待办事项对象的Promise
     */

    static async getTodoById(id) {
        try {
            const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            const todo = todos.find(item => item.id === id);
            
            if (!todo) {
                throw new Error(`找不到ID为${id}的任务`);
            }
            
            // 模拟网络延迟
            await new Promise(resolve => setTimeout(resolve, 200));
            
            return todo;
        } catch (error) {
            console.error(`获取任务ID=${id}出错:`, error);
            throw error;
        }
    }

    /**
     * 创建新的待办事项
     * @param {Object} todoData - 待办事项数据
     * @returns {Promise<Object>} 返回创建的待办事项对象的Promise
     */


    static async createTodo(todoData){
        try{
            const todos=JSON.parse(localStorage.getItem(STORAGE_KEY || '[]'))
            
            // 创建新ID
            const newTodo={
                ...todoData,
                id:Date.now(),
                created_at:new Date().toISOString()

            }
            // 添加到列表
            todo.unshift(newTodo)

            // 更新
            localStorage.setItem(STORAGE_KEY,JSON.stringify(todos))

            // 模拟网络延迟
            await new Promise(resolve =>setTimeout(resolve,300))

            return newTodo
        }catch(error){
            console.error('创建任务:',error)
            throw error
        }
    }


    /**
     * 更新待办事项
     * @param {number} id - 待办事项ID
     * @param {Object} todoData - 更新的待办事项数据
     * @returns {Promise<Object>} 返回更新后的待办事项对象的Promise
     */
    static async updateTodo(id, todoData) {
        try {
            const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            const index = todos.findIndex(todo => todo.id === id);
            
            if (index === -1) {
                throw new Error(`找不到ID为${id}的任务`);
            }
            
            // 更新任务
            const updatedTodo = {
                ...todos[index],
                ...todoData,
                updated_at: new Date().toISOString()
            };
            
            todos[index] = updatedTodo;
            
            // 更新localStorage
            localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
            
            // 模拟网络延迟
            await new Promise(resolve => setTimeout(resolve, 300));
            
            return updatedTodo;
        } catch (error) {
            console.error(`更新任务ID=${id}出错:`, error);
            throw error;
        }
    }


    /**
     * 切换待办事项完成状态
     * @param {number} id - 待办事项ID
     * @param {boolean} completed - 完成状态
     * @returns {Promise<Object>} 返回更新后的待办事项对象的Promise
     */

      static async deleteTodo(id) {
        try {
            const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            const filteredTodos = todos.filter(todo => todo.id !== id);
            
            if (filteredTodos.length === todos.length) {
                throw new Error(`找不到ID为${id}的任务`);
            }
            
            // 更新localStorage
            localStorage.setItem(STORAGE_KEY, JSON.stringify(filteredTodos));
            
            // 模拟网络延迟
            await new Promise(resolve => setTimeout(resolve, 300));
            
            return true;
        } catch (error) {
            console.error(`删除任务ID=${id}出错:`, error);
            throw error;
        }
    }



}
// 初始化存储
TodoAPI.initStorage()


// 导出API类，使其在其他模块中能用
window.TodoAPI=TodoAPI